//
//  CommentViewController.m
//  yigou
//
//  Created by 秦乾龙 on 17/1/17.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "CommentViewController.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "Comment.h"
#import "Article.h"
#import "SZTextView.h"
#import "IQKeyboardManager.h"

@interface CommentViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableArray *commentArr;
@property (assign, nonatomic) BOOL pageToEnd;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger limit;

@property (strong, nonatomic) UIView *bottombar;
@property (strong, nonatomic) SZTextView* contentTextView;
@property (strong, nonatomic) NSString *commentId;
@property (strong, nonatomic) NSString *contentId;

@end

@implementation CommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.limit = 5;
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"评论"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    _commentArr = [NSMutableArray array];
    [self setUI];
    [self makeBottomBar];
}

- (void)makeBottomBar {
    self.bottombar = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 50 - 64, ScreenWidth, 50)];
    self.bottombar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottombar];
    self.bottombar.hidden = YES;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line.backgroundColor = LineColor;
    [self.bottombar addSubview:line];
    
    UIView *border = [[UIView alloc] initWithFrame:CGRectMake(10, 10, ScreenWidth - 20, 30)];
    border.layer.masksToBounds = YES;
    border.layer.cornerRadius = 4.f;
    [border.layer setBorderWidth:1];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace, (CGFloat[]){0.9, 0.9, 0.9, 1});
    [border.layer setBorderColor:colorref];
    CGColorRelease(colorref);
    CGColorSpaceRelease(colorSpace);
    [self.bottombar addSubview:border];
    
    self.contentTextView = [[SZTextView alloc] init];
    self.contentTextView.frame = CGRectMake(0, 0, ScreenWidth - 20 - 50 - 10, 30);
    self.contentTextView.font = [UIFont systemFontOfSize:14];
    self.contentTextView.placeholder = @"说点什么";
    [border addSubview:self.contentTextView];
    //self.contentTextView.delegate = self;
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth - 20 - 50 - 1, 5, 1, 20)];
    line2.backgroundColor = LineColor;
    [border addSubview:line2];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(ScreenWidth - 20 - 50, 0, 50, 30);
    [button setTitle:@"回复" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:[UIColor colorWithHexString:@"3b3b3b"] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor whiteColor];
    [border addSubview:button];
    [button addTarget:self action:@selector(finalComment) forControlEvents:UIControlEventTouchUpInside];
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self request];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void) setUI
{
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,ScreenW , ScreenH-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    [self addRefreshHeader:_mainTableView];
    [self addLoadMoreFooter:_mainTableView];
}
//下拉刷新
- (void)refresh {
    [super refresh];
    [self request];
}
//上拉加载
- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [_mainTableView.footer endRefreshing];
        return;
    }
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/userCenter/getContentCmtList?page=%ld&limit=%ld", APIYIGOU, self.page,self.limit];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [[allDic objectForKey:@"data"] objectForKey:@"list"];
        if (array.count == 0) {
            [ViewFactory showInfoMsg:@"没有下一页了！"];
            
        }
        else if (array.count<_limit)
        {
            self.pageToEnd = YES;
        }
        self.page += 1;
        [_commentArr addObjectsFromArray: array];
        [ViewFactory dismissLoading];
        [_mainTableView reloadData];
        [_mainTableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [_mainTableView.footer endRefreshing];
    }];
}

- (void)request
{
    self.page = 1;
    self.pageToEnd = NO;
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/getContentCmtList?page=%ld&limit=%ld",APIYIGOU,self.page,self.limit]
    ;
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"allDic ====%@",allDic);
        [_commentArr removeAllObjects];
        [_commentArr addObjectsFromArray:allDic[@"data"][@"list"]];
        [_mainTableView reloadData];
        self.page += 1;
        if (_commentArr.count == 0) {
            [self showNoData];
        } else {
            [self hideNoData];
        }
        [_mainTableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _commentArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell点击背景色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    CGFloat spaceToTop = 30*kScale;
    CGFloat spaceToLeft = 30*kScale;
    CGFloat lableH = 42*kScale;
    Comment *comment = [Comment mj_objectWithKeyValues:_commentArr[indexPath.section]];
    Article *article =[Article  mj_objectWithKeyValues:_commentArr[indexPath.section][@"hyContent"]];
    UILabel *nameLable = [[UILabel alloc]init];
    nameLable.text =[NSString stringWithFormat:@"“%@”",comment.user_nike_name];
    nameLable.font = [UIFont systemFontOfSize:17];
    
    CGSize nameLableSize = [nameLable sizeThatFits:CGSizeMake(MAXFLOAT, lableH)];
    nameLable.textColor =QINGColor;
    nameLable.frame = CGRectMake(spaceToLeft, spaceToTop - 2, nameLableSize.width, nameLableSize.height);
    [cell addSubview:nameLable];

    UILabel *defultLable = [[UILabel alloc]init];
    if ([article.content_type isEqualToString:@"00"])
    {
        defultLable.text = @"评论了您的帖子";
    }
    else if ([article.content_type isEqualToString:@"01"])
    {
        defultLable.text = @"评论了您的文章";
    }
    
    defultLable.font = [UIFont systemFontOfSize:15];
    CGSize deafultSize = [defultLable sizeThatFits:CGSizeMake(MAXFLOAT, lableH)];
    defultLable.frame = CGRectMake(spaceToLeft+nameLableSize.width+10*kScale, spaceToTop, ScreenW, deafultSize.height);
    defultLable.textColor = ZallColorFromRGB(0x616161);
    [cell addSubview:defultLable];
    
    //时间
    UILabel *timeLable = [[UILabel alloc]init];
    NSDateFormatter  *dateFormatter = [[NSDateFormatter alloc]init];
    //        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:comment.comment_tm];
    NSString *finalstr = [TimeHelper intervalSinceNow:[date timeIntervalSince1970]];
    timeLable.text = finalstr;
    timeLable.font = [UIFont systemFontOfSize:12];
    CGSize timeLableSize = [timeLable sizeThatFits:CGSizeMake(MAXFLOAT, lableH)];
    timeLable.frame = CGRectMake(ScreenW-spaceToLeft-timeLableSize.width, spaceToTop, ScreenW, timeLableSize.height);
    timeLable.textColor = ZallColorFromRGB(0x616161);
    [cell addSubview:timeLable];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //button.frame = CGRectMake(ScreenW-spaceToLeft-50, spaceToTop + timeLableSize.height + 20, 50, timeLableSize.height + 10);
    [button setTitle:@"回复" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:17];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setTitleColor:QINGColor forState:UIControlStateNormal];
    button.backgroundColor = [UIColor whiteColor];
    [cell addSubview:button];
    button.tag = indexPath.section + 200;
    [button addTarget:self action:@selector(onClickComment:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 2.f;
    [button.layer setBorderWidth:1];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace, (CGFloat[]){0.05, 0.63, 0.71, 1});
    [button.layer setBorderColor:colorref];
    CGColorRelease(colorref);
    CGColorSpaceRelease(colorSpace);
    
    UILabel *commentLable = [[UILabel alloc]init];
//    contentLable.text = msg.send_content;
    commentLable.text = comment.comment;
    commentLable.numberOfLines = 1;
    commentLable.font = [UIFont systemFontOfSize:15];
    CGSize commentSize = [commentLable sizeThatFits:CGSizeMake(ScreenW-2*spaceToLeft, 42*kScale)];
    commentLable.frame = CGRectMake(spaceToLeft, spaceToTop+lableH+10*kScale, ScreenW-2*spaceToLeft, commentSize.height);
    commentLable.textColor = ZallColorFromRGB(0x000000);
    [cell addSubview:commentLable];
    
    
    CGFloat headerImageH = 164*kScale;
    UIImageView *headerImage = [[UIImageView alloc]init];
    headerImage.frame = CGRectMake(30*kScale, 15*kScale+commentLable.frame.origin.y+commentSize.height, headerImageH, headerImageH);
    [headerImage sd_setImageWithURL:[NSURL URLWithString:article.cover_img] width:140 height:140];
    
    headerImage.layer.masksToBounds  = YES;
    [cell addSubview:headerImage];
    CGFloat typeLableH = 41*kScale;
    UILabel *typeLable = [[UILabel alloc]initWithFrame:CGRectMake(0 , 0, typeLableH, typeLableH)];
    typeLable.textColor = [UIColor whiteColor];
    typeLable.backgroundColor = ZallColorFromRGB(0x000000);
    if ([article.content_type isEqualToString:@"00"])
    {
        typeLable.text = @"话";
    }
    else if ([article.content_type isEqualToString:@"01"])
    {
        typeLable.text = @"文";
    }

    
    
    typeLable.textAlignment = NSTextAlignmentCenter;
    [headerImage addSubview:typeLable];
    UILabel *introdocLable = [[UILabel alloc]init];
    introdocLable.font = [UIFont systemFontOfSize:13];
    introdocLable.numberOfLines = 0;
    //        introdocLable.lineBreakMode =  NSLineBreakByTruncatingTail;
    introdocLable.textColor = [UIColor colorWithRed:34/255.0 green:34/255.0 blue:34/255.0 alpha:1.0];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 5;
    introdocLable.text = article.content_desc;
    introdocLable.textColor = ZallColorFromRGB(0x9e9e9e);
    CGSize introSize = [introdocLable sizeThatFits:CGSizeMake(ScreenW-(headerImageH+3*30*kScale), MAXFLOAT)];
    
    //        NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:style};
    //        introdocLable.attributedText = [[NSAttributedString alloc]initWithString:introdocLable.text attributes:attributes];
    
    if (introSize.height<headerImageH)
    {
        introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, ScreenW-(headerImageH+3*30*kScale), introSize.height);
    }
    else
    {
        introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, ScreenW-(headerImageH+3*30*kScale), headerImageH);
    }
    //            introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, kScreenW-(headerImageH+3*30*kScale), introSize.height);
    
    [cell addSubview:introdocLable];
    cell.frame = CGRectMake(0, 0, ScreenW, commentLable.frame.origin.y+commentSize.height+spaceToTop+15*kScale+headerImageH);
    button.frame = CGRectMake(ScreenW-spaceToLeft-50, commentLable.frame.origin.y+commentSize.height+spaceToTop+15*kScale+headerImageH - 20 - (timeLableSize.height + 10), 50, timeLableSize.height + 10);
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(cancleSelect) withObject:nil afterDelay:0.1f];
    
    
}
- (void)cancleSelect
{
    [_mainTableView deselectRowAtIndexPath:[_mainTableView indexPathForSelectedRow] animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //提前获取cell
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    //cell里面已经设置好了frame，这里就要返回cell的frame就可以了。
    return cell.frame.size.height;
}
//设置区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0.001;
    }
    return 20*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
//修改状态栏字体
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
//返回
- (void)goPop
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onClickComment:(UIButton *)button
{
    NSInteger index = button.tag - 200;
    Comment *comment = [Comment mj_objectWithKeyValues:_commentArr[index]];
    Article *article =[Article  mj_objectWithKeyValues:_commentArr[index][@"hyContent"]];
    self.bottombar.hidden = NO;
    [self.contentTextView becomeFirstResponder];
    self.contentTextView.placeholder = [NSString stringWithFormat:@"  回复: %@",comment.user_nike_name];
    self.commentId = comment.comment_id;
    self.contentId = article.content_id;
}

- (void)finalComment {
    if(self.contentTextView.text.length == 0) {
        return;
    }
    [self AddCommentDataRequestWithReplyCommentId:self.commentId ContentId:self.contentId CommentText:self.contentTextView.text];
}

- (void)AddCommentDataRequestWithReplyCommentId:(NSString *)replyCommentId ContentId:(NSString *)contentId CommentText:(NSString *)text{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.contentTextView.text = @"";
        [self.contentTextView resignFirstResponder];
        [ViewFactory showSuccess:@"回复成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"回复失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

@end
